#include <QtGui>
#include <QDebug>
#include <iostream>
#include <QFile>
#include <QXmlStreamReader>
#include <QSqlDatabase>
#include <QSqlQuery>

#include "./include/importDlg.h"

ImportDlg::ImportDlg(QWidget *parent)
    : QDialog(parent)
{
    setWindowFlags(Qt::FramelessWindowHint);
    setFixedSize(360, 160);

    CreateWidget();

}

void ImportDlg::CreateWidget()
{
    hintLabel = new QLabel(QString::fromUtf8("请选择导入文件位置"), this);
    QFont tmpFont = hintLabel->font();
    tmpFont.setPointSize(18);
    tmpFont.setBold(true);
    hintLabel->setFont(tmpFont);

    lineEdit = new QLineEdit(this);
    lineEdit->setAttribute(Qt::WA_InputMethodEnabled, true);
    importBtn = new QPushButton(QString::fromUtf8("导入"), this);
    cancleBtn = new QPushButton(QString::fromUtf8("取消"), this);
    openFileBtn = new QPushButton(QString::fromUtf8("浏览"), this);

    importBtn->setEnabled(false);

    connect(importBtn, SIGNAL(clicked()), this, SLOT(SaveToDataBase()));
    connect(cancleBtn, SIGNAL(clicked()), this, SLOT(close()));
    connect(openFileBtn, SIGNAL(clicked()), this, SLOT(SearchFile()));
}

void ImportDlg::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.drawLine(0, 51, 360, 51);

    QPainter painterRect(this);
    painterRect.setPen(Qt::white);
    painterRect.setBrush(Qt::white);
    painterRect.drawRect(0, 0, 360, 50);

    hintLabel->setGeometry(70, 10, 300, 30);
    lineEdit->setGeometry(20, 80, 250, 24);
    openFileBtn->setGeometry(280, 80, 60, 24);
    importBtn->setGeometry(220, 120, 60, 24);
    cancleBtn->setGeometry(290, 120, 60, 24);
}

void ImportDlg::SearchFile()
{
    QString filePath = QFileDialog::getOpenFileName(
                        this,
                        QString::fromUtf8("查找文件"),
                        QDir::currentPath(),
                        "Document files (*.xml)"
                       );
    if (!filePath.isNull())
    {
        filePathStr = filePath;
        lineEdit->setText(filePath);
        importBtn->setEnabled(true);
    }
}

void ImportDlg::SaveToDataBase()
{
    ReadFile(filePathStr);
    //ImportToDataBase();
    emit importFinished();
    this->close();
}

bool ImportDlg::ReadFile(const QString &fileName)
{
    QFile file(fileName);
    if(!file.open(QFile::ReadOnly | QFile::Text))
    {
        std::cerr << "Error: Cannot read file " << qPrintable(fileName)
                  << ": " << qPrintable(file.errorString())
                  << std::endl;
        return false;
    }

    reader.setDevice(&file);

    reader.readNext();
    while(!reader.atEnd())
    {
        if(reader.isStartElement())
        {
            if(reader.name() == "itemInfo")
            {
                ReadItemInfo();
            }
            else
            {
                reader.raiseError(QObject::tr("Not a itemInfo file"));
            }
        }
        else
        {
            reader.readNext();
        }
    }

    file.close();
    if(reader.hasError())
    {
        std::cerr << "Error: Failed to parse file "
                  << qPrintable(fileName) << ". "
                  << qPrintable(reader.errorString()) << std::endl;
        return false;
    }
    else if(file.error() != QFile::NoError)
    {
        std::cerr << "Error: Cannot read file " << qPrintable(fileName)
                  << ": " << qPrintable(file.errorString())
                  << std::endl;
        return false;
    }
    return true;
}

void ImportDlg::ReadItemInfo()
{
    reader.readNext();
    while(!reader.atEnd())
    {
        if(reader.isEndElement())
        {
            reader.readNext();
            break;
        }

        if(reader.isStartElement())
        {
            if(reader.name() == "item")
            {
                ReadItem();
            }
        }
        else
        {
            reader.readNext();
        }
    }
}

void ImportDlg::ReadItem()
{
    id = reader.attributes().value("id").toString();
    qDebug() << id;

    reader.readNext();
    while(!reader.atEnd())
    {
        if(reader.isEndElement())
        {
            reader.readNext();
            ImportToDataBase();
            break;
        }

        if(reader.isStartElement())
        {
            if(reader.name() == "area")
            {
                ReadArea();
            }
            else if(reader.name() == "ridgepole")
            {
                ReadRidgePole();
            }
            else if(reader.name() == "layer")
            {
                ReadLayer();
            }
            else if(reader.name() == "room")
            {
                ReadRoom();
            }
            else if(reader.name() == "devName")
            {
                ReadDevName();
            }
        }
        else
        {
            reader.readNext();
        }
    }
}

void ImportDlg::ReadArea()
{
    area = reader.readElementText();
    if(reader.isEndElement())
    {
        reader.readNext();
    }
}

void ImportDlg::ReadRidgePole()
{
    ridgepole = reader.readElementText();
    if(reader.isEndElement())
    {
        reader.readNext();
    }
}

void ImportDlg::ReadLayer()
{
    layer = reader.readElementText();
    if(reader.isEndElement())
    {
        reader.readNext();
    }
}

void ImportDlg::ReadRoom()
{
    room = reader.readElementText();
    if(reader.isEndElement())
    {
        reader.readNext();
    }
}

void ImportDlg::ReadDevName()
{
    devName = reader.readElementText();
    if(reader.isEndElement())
    {
        reader.readNext();
    }
}

void ImportDlg::ImportToDataBase()
{
    QSqlDatabase::database().transaction();
    QSqlQuery query;

    query.exec(QString("insert into itemInfo values('%1', '%2', '%3', '%4', '%5', '%6')"
                       ).arg(id).arg(area).arg(ridgepole).arg(layer).arg(room).arg(devName));

    QSqlDatabase::database().commit();
}
